<?php

require_once 'classes/cls_Database.php';

class StatServer
{
    public function __construct()
    {
        Db::setConnectionInfo('db/atac.sqlite', null, null, 'sqlite');
    }

    function createTemplate()
    {
        $host = 'http://' . Db::getValue('SELECT server_name FROM atac_statserver') . ':' . Db::getValue('SELECT port FROM atac_statserver');

        $googles = Db::getResult('SELECT message_text FROM atac_messages WHERE message_alert = ?', 'google');
        $glist = array();
        foreach ($googles as $k => $v) {
            if (!empty($v['message_text'])) {
                if (!in_array($v['message_text'], $glist)) {
                    $glist[] = $v['message_text'];
                }
            }
        }
        // link them all
        foreach ($glist as $k => $v) $glist[$k] = '<a href="http://www.google.com/search?hl=en&source=atac&q='.$v.'">'.$v.'</a>';

        $_alerts = '';
        $counts = array();
        $_adata = Db::getResult('SELECT message_alert, message_text FROM atac_messages');
        foreach ($_adata as $k => $v) {
            // make sure it's not a normal message
            if (!empty($v['message_alert'])) {
                if (!array_key_exists($v['message_alert'], $counts)) {
                    $counts[$v['message_alert']] = 1;
                } else {
                    $counts[$v['message_alert']]+=1;
                }
            }
        }
        arsort($counts);
        foreach($counts as $k => $v) $_alerts.= '<tr><td>'.$k.'</td><td>'.$v.'</td></tr>';

        $_messages = '';
        $mcount = array();
        $_mdata = Db::getResult('SELECT screenname, COUNT(screenname) as count FROM atac_messages GROUP BY screenname');
        asort($_mdata);
        foreach ($_mdata as $k => $v) {
            $_messages.= '<tr><td>'.$v['screenname'].'</td><td>'.$v['count'].'</td></tr>';
        }

        $twits = Db::getResult('SELECT message_text FROM atac_messages WHERE message_alert = ?', 'tweetget');
        $tlist = array();
        foreach ($twits as $t => $z) {
            if (!empty($z['message_text'])) {
                if (!in_array($z['message_text'], $tlist)) {
                    if ($z['message_text'] != '--help') $tlist[] = $z['message_text'];
                }
            }
        }
        // link them all
        foreach ($tlist as $k => $v) $tlist[$k] = '<a href="http://www.twitter.com/'.$v.'">'.$v.'</a>';

        $replace = array(
            '%%host%%'          =>  $host,
            '%%total_msgs%%'    =>  Db::getValue('SELECT COUNT(*) as count FROM atac_messages'),
            '%%first_run%%'     =>  date('F j, Y, \@ g:i a', Db::getValue('SELECT firstrun FROM atac_stats')),
            '%%last_run%%'      =>  date('F j, Y, \@ g:i a', Db::getValue('SELECT signon FROM atac_stats')),
            '%%screenname%%'    =>  Db::getValue('SELECT screenname FROM atac_stats'),
            '%%google_res%%'    =>  join('<br />', $glist),
            '%%phpos%%'         =>  PHP_OS,
            '%%phpversion%%'    =>  phpversion(),
            '%%alert_table%%'   =>  $_alerts,
            '%%message_table%%' =>  $_messages,
            '%%twitters%%'      =>  join('<br />', $tlist),
        );

        $_tdata = file_get_contents('data/StatServerTemplate.html');
        foreach ($replace as $k => $v) $_tdata = str_replace($k, $v, $_tdata);

        return $_tdata;
    }

    function parseHeaders($header)
    {
        $retVal = array();
        $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
        foreach( $fields as $field ) {
            if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
                $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
                if( isset($retVal[$match[1]]) ) {
                    $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
                } else {
                    $retVal[$match[1]] = trim($match[2]);
                }
            }
        }
        return $retVal;
    }

    function Recieve($idle = 5)
    {
        $server = Db::getValue('SELECT server FROM atac_statserver');
        $port   = Db::getValue('SELECT port FROM atac_statserver');
        if (!$socket = stream_socket_server('tcp://' . $server . ':' . $port, $errno, $errstr)) {
            echo "StatServer Error: $errstr ($errno)<br />\n";
        } else {
            while ($conn = @stream_socket_accept($socket, $idle)) {
                $message = fread($conn, 1024);
                var_dump($this->parseHeaders($message));
                // response
                fputs ($conn, $this->createTemplate());
                fclose ($conn);
            }
            fclose($socket);
        }
    }
}

$s = new StatServer();
// run the loop
while (true) {
    // disconnected every 5 seconds...
    $s->Recieve();
}

?>